
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from django.db import models
from django.utils import timezone

from utils.exception import CustomError


# Create your models here.

class UserManager(BaseUserManager):
    def create_user(self, username, password=None, **extra_fields):
        if username is None:
            raise CustomError("请输入手机号！")
        user = self.model(username=username, is_superuser=False,type=User.MEMBER, last_login=timezone.now(), **extra_fields)

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, password, **extra_fields):
        user = self.create_user(username, password, **extra_fields)
        user.is_active = True
        user.is_superuser = True
        user.type = User.ADMINSTARTOR
        user.save(using=self._db)
        return user


class User(AbstractBaseUser, PermissionsMixin):
    FEMAL = 1
    MALE = 2
    GENDER_CHOICES = (
        (FEMAL, '女'),
        (MALE, '男')
    )

    ADMINSTARTOR = 1
    MEMBER = 2
    TYPE_CHOICES = (
        (ADMINSTARTOR, '管理员'),
        (MEMBER, '会员')
    )

    type = models.PositiveSmallIntegerField(choices=TYPE_CHOICES, verbose_name='类型', default=MEMBER)
    username = models.CharField(verbose_name="账号", max_length=30, unique=True,
                                db_index=True)  # db_index=True 则代表着为此字段设置索引。
    nickname = models.CharField(verbose_name="昵称", max_length=100, null=True, blank=True)
    gender = models.PositiveSmallIntegerField(choices=GENDER_CHOICES, verbose_name='性别', null=True)
    create_time = models.DateTimeField(verbose_name='注册时间', auto_now_add=True,
                                       editable=False)  # 如果为False，则该字段将不会显示在admin或其他ModelForm。在模型验证期间也将跳过它们
    # roles = models.ManyToManyField(Role, verbose_name='拥有角色')

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = []

    def __unicode__(self):
        return self.nickname or self.username

    def is_administrator(self):
        if self.type == self.ADMINSTARTOR:
            return True
        return False

    @property
    def is_staff(self):
        return self.is_administrator()

    def is_member(self):
        if self.type == self.MEMBER:
            return True
        return False

    class Meta:
        db_table = "auth_user"
        verbose_name = "账号"
        unique_together = [
            ('username')
        ]
        ordering = ['-id']
